package com.jinzhi.jzweb.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.utils.ApiResult;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.ShiroUtils;
import com.jinzhi.jzapi.utils.CerSynthesisUtil;
import com.jinzhi.jzweb.dao.CertificateInfoDao;
import com.jinzhi.jzweb.dao.WorkExperinceDao;
import com.jinzhi.jzweb.domain.CertificateInfoDO;
import com.jinzhi.jzweb.domain.WorkExperinceDO;
import com.jinzhi.jzweb.domain.cond.CertificateInfoCond;
import com.jinzhi.jzweb.domain.cond.InformationImportUserCond;
import com.jinzhi.jzweb.domain.cond.WorkExperinceCond;
import com.jinzhi.jzweb.domain.vo.CertificateInfoVo;
import com.jinzhi.jzweb.domain.vo.InformationImportUserVo;
import com.jinzhi.jzweb.domain.vo.WorkExperinceVo;
import com.jinzhi.jzweb.service.WorkExperinceService;
import com.jinzhi.jzweb.utils.ValuesUtil;
import com.jinzhi.sys.dao.UserDao;
import com.jinzhi.sys.domain.UserDO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jinzhi.jzweb.dao.InformationImportUserDao;
import com.jinzhi.jzweb.domain.InformationImportUserDO;
import com.jinzhi.jzweb.service.InformationImportUserService;
import com.jinzhi.common.base.CoreServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <pre>
 *
 * </pre>
 * <small> 2024-05-15 17:22:11 | lance</small>
 */
@Service
public class InformationImportUserServiceImpl extends CoreServiceImpl<InformationImportUserDao, InformationImportUserDO> implements InformationImportUserService {

    @Autowired
    private WorkExperinceService workExperinceService;
    @Autowired
    private InformationImportUserDao informationImportUserDao;
    @Autowired
    private CertificateInfoDao certificateInfoDao;
    @Autowired
    private WorkExperinceDao workExperinceDao;
    @Autowired
    private UserDao userDao;

    // 用户信息相关

    public UserDO getUser() {
        return ShiroUtils.getSysUser();
    }

    public Long getUserId() {
        return getUser().getId();
    }

    @Override
    public ApiResult<?> saveSignUserInfo(UserDO userDO, InformationImportUserCond cond) {
        InformationImportUserDO informationImportUserDO1 = this.selectOne(new EntityWrapper<InformationImportUserDO>().eq("mobile", userDO.getMobile()).eq("declared_careers", cond.getDeclaredCareers()).eq("exam_time", cond.getExamTime()));
        if (informationImportUserDO1 != null) {
            return ApiResult.fail("当前申报职业已存在用户信息！");
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate born = LocalDate.parse(cond.getBorn(), formatter);
        InformationImportUserDO informationImportUserDO = new InformationImportUserDO();
        BeanUtils.copyProperties(cond, informationImportUserDO);
        informationImportUserDO.setDeclaredSubject(cond.getDeclaredSubject());
        informationImportUserDO.setCreateTime(LocalDateTime.now());
        informationImportUserDO.setBorn(born);
        informationImportUserDO.setExamTime(cond.getExamTime());
        informationImportUserDO.setCheckStatus(0);
        List<WorkExperinceCond> experinceConds = cond.getExperinceConds();
        if (userDO != null) {
            informationImportUserDO.setUserId(userDO.getId());
            informationImportUserDO.setMobile(userDO.getMobile());
        }
        if (cond.getExperinceConds().isEmpty()) {
            informationImportUserDO.setWorkTime("0");
        } else {
            int i = calculateTotalWorkExperience(experinceConds);
            //workTime 工作年限
            informationImportUserDO.setWorkTime(String.valueOf(i));
        }

        informationImportUserDao.insert(informationImportUserDO);
        return ApiResult.success();
    }


    //获取职业年限时间
    public static int calculateTotalWorkExperience(List<WorkExperinceCond> workExperiences) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        int totalMonths = 0;

        for (WorkExperinceCond experience : workExperiences) {
            LocalDate startDate = LocalDate.parse(experience.getStartTime(), formatter);
            LocalDate endDate = LocalDate.parse(experience.getEndTime(), formatter);

            // 计算开始日期和结束日期之间的差额
            Period period = Period.between(startDate, endDate);
            int years = period.getYears();
            int months = period.getMonths();
            int days = period.getDays();

            // 将年数和月数转换为总的月数
            totalMonths += years * 12 + months;

            // 如果有剩余的天数，并且天数大于15天，则算作一个月
            if (days > 20) {
                totalMonths++;
            }
        }

        // 将总的月份数转换为年数
        int totalYears = totalMonths / 12;
        // 返回绝对值
        return Math.abs(totalYears);
    }


    @Override
    public String savePdf(Long id, String traSynthesis, String electronic) {
        //表格图片
        String cerImgUrl = null;
        String cerImgUrlNoSale = null;
        //获取已审核完成的用户信息
        InformationImportUserVo info = getInfo1(id);
        try {

            //参数说明：合成类型（0带寸照，1不带寸照），用户数据 公章先不做
//            cerImgUrl = CerSynthesisUtil.jinzhiPdf(0,info,traSynthesis,electronic);
            cerImgUrl = CerSynthesisUtil.fillPdf(info, traSynthesis, electronic);
            System.out.println("外面返回的url" + cerImgUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }


        //转换一下图片路径，将反斜杠替换掉
        String url = cerImgUrl.replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
        String imgUrl1 = url.replace("\\", "/");

//        certificateInfoDO.setPhoto(imgUrl1);//证书图片
//        if (schoolCerUtilsVOS.get(i).getElectronicSealType() == 1) {
//            //转换一下图片路径，将反斜杠替换掉
//            String url1 = cerImgUrlNoSale.replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
//            String imgUrl2 = url1.replace("\\", "/");
//            schoolCertificatesDOList.get(i).setImgUrlNosale(imgUrl2);//不带电子公章的证书图片链接
//        }


        System.out.println("修改成功-----");
        return imgUrl1;
    }

    @Override
    public Result<Page<InformationImportUserDO>> selImportUserList(String name, String mobile, int current, int size, String createTime, String endTime, Integer personType, Integer checkStatus, String examTime, String declaredCareers) {
        Page<InformationImportUserDO> page = new Page<>(current, size);
        List<InformationImportUserDO> voList = new ArrayList<>();
        Wrapper<InformationImportUserDO> wrapper = new EntityWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            wrapper.like("name", "%"+name+"%");
        }
        if (StringUtils.isNotBlank(mobile)) {
            wrapper.like("mobile", "%"+mobile+"%");
        }
        if (checkStatus != null && checkStatus != -1) {
            wrapper.eq("check_status", checkStatus);
        }
        if (personType != null && personType != -1) {
            wrapper.eq("person_type", personType);
        }
        if (StringUtils.isNotBlank(createTime) && StringUtils.isNotBlank(endTime)) {
            wrapper.between("create_time", createTime, endTime);
        }
        if (StringUtils.isNotBlank(examTime)) {
            wrapper.like("exam_time", "%"+examTime+"%");
        }
        if (StringUtils.isNotBlank(declaredCareers)) {
            wrapper.like("declared_careers", "%"+declaredCareers+"%");
        }
        wrapper.orderBy("create_time", false);
        Page<InformationImportUserDO> informationImportUserDOPage = this.selectPage(page, wrapper);
        for (InformationImportUserDO informationImportUserDO : informationImportUserDOPage.getRecords()) {
            InformationImportUserDO vo = new InformationImportUserDO();
            BeanUtils.copyProperties(informationImportUserDO, vo);
            voList.add(vo);
        }
        informationImportUserDOPage.setRecords(voList);
        return Result.ok(informationImportUserDOPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult<?> updateImportUser(InformationImportUserCond cond, UserDO userDO) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate born = LocalDate.parse(cond.getBorn(), formatter);
        InformationImportUserDO informationImportUserDO = this.selectById(cond.getId());
        if (!Objects.equals(informationImportUserDO.getDeclaredCareers(), cond.getDeclaredCareers())||!Objects.equals(informationImportUserDO.getExamTime(), cond.getExamTime())){
            InformationImportUserDO informationImportUserDO1 = this.selectOne(new EntityWrapper<InformationImportUserDO>().eq("mobile",userDO.getMobile()).eq("declared_careers", cond.getDeclaredCareers()).eq("exam_time", cond.getExamTime()));
            if (informationImportUserDO1 != null) {
                return ApiResult.fail("当前申报职业已存在用户信息！");
            }
        }

        BeanUtils.copyProperties(cond, informationImportUserDO);
        informationImportUserDO.setUpdateTime(LocalDateTime.now());

        informationImportUserDO.setBorn(born);
        informationImportUserDO.setExamTime(cond.getExamTime());
        //获取用户信息
        List<WorkExperinceCond> experinceConds = cond.getExperinceConds();
//        List<CertificateInfoCond> certificateInfoConds = cond.getCertificateInfoConds();
        if (userDO != null) {
            informationImportUserDO.setUpdateId(userDO.getId());
            informationImportUserDO.setMobile(userDO.getMobile());
        }
        int i = calculateTotalWorkExperience(experinceConds);
        informationImportUserDO.setWorkTime(String.valueOf(i));
        informationImportUserDO.setCheckStatus(0);
        this.updateById(informationImportUserDO);
        return ApiResult.success();
    }

    @Override
    public InformationImportUserVo getInfo1(Long id) {
        InformationImportUserVo vo = new InformationImportUserVo();

        InformationImportUserDO informationImportUserDO = this.selectById(id);
        BeanUtils.copyProperties(informationImportUserDO, vo);
        vo.setEducation(informationImportUserDO.getEducation());
        List<CertificateInfoDO> certificatesDOS = certificateInfoDao.selectList(new EntityWrapper<CertificateInfoDO>().eq("info_user_id", informationImportUserDO.getUserId()));
        List<CertificateInfoVo> voList = new ArrayList<>();
        certificatesDOS.forEach(e -> {
            CertificateInfoVo vo1 = new CertificateInfoVo();
            BeanUtils.copyProperties(e, vo1);
            vo1.setLevel(e.getLevel());
            voList.add(vo1);
        });
        vo.setCertificateInfoVos(voList);

        List<WorkExperinceDO> experinceDOS = workExperinceDao.selectList(new EntityWrapper<WorkExperinceDO>().eq("info_user_id", informationImportUserDO.getUserId()));
        List<WorkExperinceVo> vos = new ArrayList<>();
        experinceDOS.forEach(e -> {
            WorkExperinceVo vo1 = new WorkExperinceVo();
            BeanUtils.copyProperties(e, vo1);

            vo1.setEndTime(e.getEndTime().toString().replace("-", "/"));
            vo1.setStartTime(e.getStartTime().toString().replace("-", "/"));
            vos.add(vo1);
        });
        vo.setExperinceVos(vos);
        return vo;
    }

    @Override
    public Result<String> updateImportUser1(InformationImportUserCond cond) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        InformationImportUserDO informationImportUserDO = this.selectById(cond.getId());
        if (!Objects.equals(informationImportUserDO.getDeclaredCareers(), cond.getDeclaredCareers())||!Objects.equals(informationImportUserDO.getExamTime(), cond.getExamTime())){
            InformationImportUserDO informationImportUserDO1 = this.selectOne(new EntityWrapper<InformationImportUserDO>().eq("mobile", cond.getMobile()).eq("declared_careers", cond.getDeclaredCareers()).eq("exam_time", cond.getExamTime()));
            if (informationImportUserDO1 != null) {
                return Result.fail("当前申报职业已存在用户信息！");
            }
        }
        BeanUtils.copyProperties(cond, informationImportUserDO);
        informationImportUserDO.setUpdateTime(LocalDateTime.now());
        List<WorkExperinceCond> experinceConds = cond.getExperinceConds();
        List<CertificateInfoCond> certificateInfoConds = cond.getCertificateInfoConds();
        UserDO userDO = new UserDO();
        userDO.setMobile(cond.getMobile());
        //查到要填写的人员信息
        UserDO userDO1 = userDao.selectOne(userDO);
        if (userDO1 == null) {
            return  Result.fail("小程序未登录，用户没有查询到");
        }
        informationImportUserDO.setUserId(userDO1.getId());
        informationImportUserDO.setUpdateId(this.getUserId());
        for (WorkExperinceCond cond1 : experinceConds) {
            WorkExperinceDO workExperinceDO = new WorkExperinceDO();
            BeanUtils.copyProperties(cond1, workExperinceDO);
            LocalDate start = LocalDate.parse(cond1.getEndTime(), formatter);
            LocalDate end = LocalDate.parse(cond1.getStartTime(), formatter);
            workExperinceDO.setStartTime(start);
            workExperinceDO.setEndTime(end);
            workExperinceDO.setInfoUserId(userDO1.getId());
            if (cond1.getIsDelete() != null && cond1.getId() != null) {
                // 先判断是否需要删除
                workExperinceDao.deleteById(cond1.getId());
            } else if (cond1.getId() != null) {
                // 然后判断ID是否存在，存在则更新
                workExperinceDO.setId(cond1.getId());
                workExperinceDao.updateById(workExperinceDO);
            } else {
                // ID不存在，说明是新记录，执行插入
                workExperinceDao.insert(workExperinceDO);
            }
        }
        for (CertificateInfoCond cond1 : certificateInfoConds) {
            CertificateInfoDO infoDO = new CertificateInfoDO();
            BeanUtils.copyProperties(cond1, infoDO);
            LocalDate parse = LocalDate.parse(cond1.getCertificateTime(), formatter1);
            infoDO.setCertificateTime(parse);
            infoDO.setInfoUserId(userDO1.getId());
            if (cond1.getIsDelete() != null && cond1.getId() != null) {
                // 先判断是否需要删除
                certificateInfoDao.deleteById(cond1.getId());
            } else if (cond1.getId() != null) {
                // 然后判断ID是否存在，存在则更新
                infoDO.setId(cond1.getId());
                certificateInfoDao.updateById(infoDO);
            } else {
                // ID不存在，说明是新记录，执行插入
                certificateInfoDao.insert(infoDO);
            }
        }
        int i = calculateTotalWorkExperience(experinceConds);
        informationImportUserDO.setWorkTime(String.valueOf(i));
        this.updateById(informationImportUserDO);

        return  Result.ok();
    }

    @Override
    public Result<String> saveSignUserInfo1(InformationImportUserCond cond) {
        InformationImportUserDO informationImportUserDO1 = this.selectOne(new EntityWrapper<InformationImportUserDO>().eq("mobile", cond.getMobile()).eq("declared_careers", cond.getDeclaredCareers()).eq("exam_time", cond.getExamTime()));
        if (informationImportUserDO1 != null) {
            return Result.fail("当前申报职业已存在用户信息！");
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        LocalDate born = LocalDate.parse(cond.getBorn(), formatter);
        InformationImportUserDO informationImportUserDO = new InformationImportUserDO();
        BeanUtils.copyProperties(cond, informationImportUserDO);
        informationImportUserDO.setDeclaredSubject(cond.getDeclaredSubject());
        informationImportUserDO.setCreateTime(LocalDateTime.now());
        informationImportUserDO.setBorn(born);
        informationImportUserDO.setExamTime(cond.getExamTime());
        informationImportUserDO.setCheckStatus(0);
        List<WorkExperinceCond> experinceConds = cond.getExperinceConds();
        //证书信息
        List<CertificateInfoCond> certificateInfoConds = cond.getCertificateInfoConds();
        UserDO userDO1 = new UserDO();
        userDO1.setMobile(cond.getMobile());
        //查到要填写的人员信息
        UserDO userDO2 = userDao.selectOne(userDO1);
//            if (userDO2==null){
//                return "小程序未登录，用户没有查询到";
//            }
        informationImportUserDO.setUserId(userDO2.getId());
//            //查询信息录入表是否存在相同数据
//            InformationImportUserDO informationImportUserDO2 = this.selectOne(new EntityWrapper<InformationImportUserDO>().eq("user_id", userDO2.getId()).eq("declared_careers",cond.getDeclaredCareers()));
//            if (informationImportUserDO2!=null){
//                return "已经存在该手机号录入的信息";
//            }
        //后台传输
        certificateInfoConds.forEach(e -> {
            CertificateInfoDO certificatesDO = new CertificateInfoDO();
            BeanUtils.copyProperties(e, certificatesDO);
            certificatesDO.setInfoUserId(userDO2.getId());
            LocalDate parse = LocalDate.parse(e.getCertificateTime(), formatter);
            certificatesDO.setCertificateTime(parse);
            certificateInfoDao.insert(certificatesDO);
        });
        experinceConds.forEach(e -> {
            WorkExperinceDO workExperinceDO = new WorkExperinceDO();
            BeanUtils.copyProperties(e, workExperinceDO);
            BeanUtils.copyProperties(e, workExperinceDO);
            LocalDate start = LocalDate.parse(e.getEndTime(), formatter1);
            LocalDate end = LocalDate.parse(e.getStartTime(), formatter1);
            workExperinceDO.setStartTime(start);
            workExperinceDO.setEndTime(end);
            workExperinceDO.setInfoUserId(userDO2.getId());
            workExperinceDao.insert(workExperinceDO);
        });

        if (cond.getExperinceConds().isEmpty()) {
            informationImportUserDO.setWorkTime("0");
        } else {
            int i = calculateTotalWorkExperience(experinceConds);
            //workTime 工作年限
            informationImportUserDO.setWorkTime(String.valueOf(i));
        }


        informationImportUserDao.insert(informationImportUserDO);
        return Result.ok();
    }

    @Override
    public List<InformationImportUserVo> getInfos(UserDO user, Integer checkStatus, String declaredCareers) {
        List<InformationImportUserVo> voList = new ArrayList<>();
        Wrapper<InformationImportUserDO> wrapper = new EntityWrapper<InformationImportUserDO>().eq("user_id", user.getId());
        if (checkStatus != null) {
            wrapper.eq("check_status", checkStatus);
        }
        if (StringUtils.isNotBlank(declaredCareers)) {
            wrapper.eq("declared_careers", declaredCareers);
        }
        List<InformationImportUserDO> informationImportUserDOS = this.selectList(wrapper);
        if (!informationImportUserDOS.isEmpty()) {
            informationImportUserDOS.forEach(informationImportUserDO -> {
                InformationImportUserVo vo = new InformationImportUserVo();
                BeanUtils.copyProperties(informationImportUserDO, vo);
                vo.setEducation(informationImportUserDO.getEducation());
                vo.setName(informationImportUserDO.getName());
                vo.setMobile(informationImportUserDO.getMobile());
                List<CertificateInfoDO> certificatesDOS = certificateInfoDao.selectList(new EntityWrapper<CertificateInfoDO>().eq("info_user_id", user.getId()));
                List<CertificateInfoVo> voList1 = new ArrayList<>();
                certificatesDOS.forEach(e -> {
                    CertificateInfoVo vo1 = new CertificateInfoVo();
                    BeanUtils.copyProperties(e, vo1);
                    vo1.setLevel(e.getLevel());
                    voList1.add(vo1);
                });
                vo.setCertificateInfoVos(voList1);

                List<WorkExperinceDO> experinceDOS = workExperinceDao.selectList(new EntityWrapper<WorkExperinceDO>().eq("info_user_id", user.getId()));
                List<WorkExperinceVo> vos = new ArrayList<>();
                experinceDOS.forEach(e -> {
                    WorkExperinceVo vo1 = new WorkExperinceVo();
                    BeanUtils.copyProperties(e, vo1);

                    vo1.setEndTime(e.getEndTime().toString().replace("-", "/"));
                    vo1.setStartTime(e.getStartTime().toString().replace("-", "/"));
                    vos.add(vo1);
                });
                vo.setExperinceVos(vos);
                voList.add(vo);
            });

        }


        return voList;
    }

}
